<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- <PageTools :show-before="true"> -->
      <PageTools show-before>
        <template #before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template #after>
          <el-button type="success" size="small" @click="$router.push('/import')">Excel导入</el-button>
          <el-button type="danger" size="small" @click="exportData">Excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <!-- 显示头像 -->
          <el-table-column label="头像">
            <template v-slot="{row}">
              <img
                v-imgerror='default_img'
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>

          <el-table-column label="工号" sortable="" prop="workNumber" />
          <!-- 通过过滤器格式化"聘用形式" -->
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment">
            <template v-slot="{ row }">
              {{ row.formOfEmployment|formofEmployment1 }}
            </template>
          </el-table-column>

          <el-table-column label="部门" sortable="" prop="departmentName" />

          <!-- <el-table-column label="入职时间" sortable="" prop="timeOfEntry" /> -->
          <el-table-column label="入职时间" sortable="" align="center">
            <!-- 作用域插槽 -->
            <template slot-scope="{ row }">{{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>

          <!-- <el-table-column label="账户状态" sortable="" prop="enableState" /> -->
          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>

          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码标签 -->
        <el-row type="flex" justify="center" align="middle" style="height:60px">
          <el-pagination layout="prev,pager,next" :total="page.total" :page-size="page.size" @current-change="changePage"></el-pagination>
        </el-row>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog"></add-employee>
    <!-- 头像二维码弹层 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>

    <!-- 角色选择弹窗 -->
    <AssignRole ref="assiginRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId"></AssignRole>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import { pick } from 'lodash'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
import default_img from '@/assets/common/bigUserHeader.png'
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  filters: {
    formofEmployment1(val) {
      const f = EmployeeEnum.hireType.find(t => t.id === val)
      return f ? f.value : '未知'
    }
  },
  props: {},
  data() {
    // const default_img = require('@/assets/common/bigUserHeader.png')
    return {
      default_img,
      loading: false,
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 10, // 每页数量
        total: 0 // 总数
      },
      showDialog: false, // 新增员工弹层显示隐藏
      showCodeDialog: false, // 头像二维码显示隐藏
      showRoleDialog: false, // 角色分配弹层组件显示隐藏
      userId: null // 人员id
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 控制角色弹层
    async editRole(row) {
      // console.log(row)
      this.userId = row.id
      // console.log(id)
      await this.$refs.assiginRole.getUserDetailById(row.id) // 调用子组件的方法
      this.showRoleDialog = true
    },
    // 弹出二维码的方法
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 页面的渲染是异步的
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 导出excel表格
    exportData() {
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取所有数据，size==this.page.total
        // const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const { rows } = await getEmployeeList({ page: 1, size: 10 })
        console.log(rows)// [{英文键：值},{英文键：值},{英文键：值}...]
        // 所有的英文头['username','mobile',...]
        const values = Object.values(headers)
        // 得到数据
        const results = rows.map(o => {
          // lodash里面pick方法将原始数据按照values的顺序和键名筛选出来
          const t = pick(o, values)
          // 日期格式化
          t.timeOfEntry = formatDate(t.timeOfEntry)
          t.correctionTime = formatDate(t.correctionTime)
          // 聘用形式格式化
          const f = EmployeeEnum.hireType.find(m => m.id === t.formOfEmployment)
          t.formOfEmployment = f ? f.value : '未知'
          return Object.values(t)
        })
        console.log(results) // [[],[],[]...]
        // 复杂表头两个参数
        // https://gitee.com/panjiachen/vue-element-admin/blob/master/src/views/excel/merge-header.vue
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        // 得到映射数据excel表格并下载
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: results, // 具体数据 必填 [[],[][]]
          filename: '员工信息表', // 非必填 文件名
          autoWidth: true, // 自适应宽度
          bookType: 'xlsx', // 导出文件格式
          // 复杂表头配置项
          multiHeader,
          merges
        })
      })
    },
    // 删除员工
    delEmployee(id) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(async action => {
        console.log(action) // confirm
        // 发请求
        await delEmployee(id)
        // 提示成功
        this.$message({
          message: '操作成功！',
          type: 'success',
          showClose: true,
          duration: 3000 // 持续时间
        })
        // 刷新页面
        this.getEmployeeList()
      }).catch((e) => {
        console.log(e) // cancel
      })
    },
    // 点击分页 的处理函数
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 获取数据列表
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    formAtEmployment(row, column, val, index) {
      const f = EmployeeEnum.hireType.find(t => t.id === val)
      return f ? f.value : '未知'
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
